package com.scpii.universal.struts.produce;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.scpii.universal.action.BaseAction;
import com.scpii.universal.constant.ExceptionConstants;
import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.dto.PageNavigationDto;
import com.scpii.universal.dto.SortColumnsDto;
import com.scpii.universal.dto.TypeDto;
import com.scpii.universal.hibernate.entity.AppIconTab;
import com.scpii.universal.hibernate.entity.AppPageTab;
import com.scpii.universal.hibernate.entity.AppViewCatelogRalationTab;
import com.scpii.universal.hibernate.entity.AttributeTab;
import com.scpii.universal.hibernate.entity.CatelogTab;
import com.scpii.universal.hibernate.entity.ModuleStyleTab;
import com.scpii.universal.hibernate.entity.PageNavigationTab;
import com.scpii.universal.pns.entity.Field;
import com.scpii.universal.pns.service.FieldService;
import com.scpii.universal.service.AppIconService;
import com.scpii.universal.service.AppPageService;
import com.scpii.universal.service.DataSortService;
import com.scpii.universal.service.MoreContentService;
import com.scpii.universal.service.PageNavigationService;
import com.scpii.universal.util.FileUploadUtil;
import com.scpii.universal.util.ImgAndFilePath;

/**
 * UniversalWeb
 * @author liuhj
 * 2012-7-6上午09:22:10
 */
@Controller
@Scope("prototype")
public class PageProcessAction extends BaseAction {

	private static final long serialVersionUID = -2166116208003512954L;
	@Resource
	private PageNavigationService pageNavigationService;
	@Resource
	private AppPageService appPageService;
	@Resource
	private AppIconService appIconService;
	@Resource
	private MoreContentService moreContentService;
	@Resource
	private DataSortService dataSortService;
	@Resource
	private FieldService fieldService;
	private String json;
	private List<PageNavigationTab> listPageNavigation;
	private Integer id;
	private List<AppPageTab> lstAppPage;
	private List<AppIconTab> lstAppIcon;
	private String imgIconUrl;
	private List<ModuleStyleTab> lstModuleSytle;
	private AppIconTab appIcon;
	private List<PageNavigationDto> lstPageNavigationDto;
	private List<AttributeTab> lstAttributes;
	private List<TypeDto> lstTypes;
	private List<SortColumnsDto> sortColumns;
	private List<Field> userFields;
	
	/**
	 * 保存或新增导航
	 * @return
	 * @author liuhj
	 * 2012-7-16上午10:17:00
	 * @throws IOException 
	 */
	public String savePageNavigation() throws IOException {
		json = URLDecoder.decode(json, "GBK");
		json = json.trim().substring(1, json.length() - 1).replaceAll("\\\\","");
		List<PageNavigationTab> lstNavigations = new ArrayList<PageNavigationTab>();
		JSONObject jo = JSONObject.fromObject(json);
		String errMsg = validateNavigation(jo.get("navigationInfo").toString(),
				lstNavigations);
		if (errMsg != null) {
			jsonOut(errMsg);
			return null;
		}
		pageNavigationService.saveOrUpdatePatch(lstNavigations, getUserInfo(), jo);
		jsonOut(GenericConstants.OPERATION_SUCCESS);
		return null;
	}
	
	/**
	 * 校验导航的信息
	 * @param json
	 * @return
	 * @author liuhj
	 * 2012-7-20上午09:21:26
	 */
	private String validateNavigation(String json,List<PageNavigationTab> lstNavigations) {
		JSONArray ja = JSONArray.fromObject(json);
		String errMsg = null;
		for (int i = 0; i < ja.size(); i++) {
			PageNavigationTab pageNavigationTab = (PageNavigationTab) JSONObject
					.toBean(JSONObject.fromObject(ja.get(i)),PageNavigationTab.class);
			if (StringUtils.isBlank(pageNavigationTab.getVarNavigateName())) {
				errMsg = ExceptionConstants.NAVIGATION_NAME_NULL_ERROR;
				lstNavigations = null;
				return errMsg;
			}
			if (pageNavigationTab.getIntNavigateIconId() == null) {
				errMsg = ExceptionConstants.NAVIGATION_ICON_NULL_ERROR;
				lstNavigations = null;
				return errMsg;
			}
			lstNavigations.add(pageNavigationTab);
		}
		return errMsg;
	}
	
	/**
	 * 查看应用导航
	 * @return
	 * @throws IOException
	 * @author liuhj
	 * 2012-7-14上午11:12:40
	 */
	public String viewPageNavigation() throws IOException {
		if (getUserInfo().getAppId() == null || getUserInfo().getAppId() == 0) {
			return null;
		}
		List<PageNavigationDto> navigations = pageNavigationService
				.listAllNavigation(getUserInfo().getAppId());
		if (navigations == null) {
			// 该应用还没导航记录
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		} else {
			this.setLstPageNavigationDto(navigations);
			return SUCCESS;
		}
	}
	
	/**
	 * 删除导航
	 * @return
	 * @throws IOException
	 * @author liuhj
	 * 2012-7-14下午12:10:45
	 */
	public String deletePageNavigation() throws IOException {
		int navId = JSONObject.fromObject(json).getInt("id");
		if (navId != -1) {
			appPageService.deleteNavigation(navId);
		}
		jsonOut(GenericConstants.OPERATION_SUCCESS);
		return null;
	}
	
	/**
	 * 删除页面
	 * @return
	 * @throws IOException
	 * @author liuhj
	 * 2012-7-14下午12:10:45
	 */
	public String deletePage() throws IOException {
		int pageId = JSONObject.fromObject(json).getInt("id");
		if (pageId != -1) {
			appPageService.deletePage(pageId);
		}
		jsonOut(GenericConstants.OPERATION_SUCCESS);
		return null;
	}
	
	/**
	 * 根据导航获得所有子页面
	 * @return
	 * @author liuhj
	 * 2012-7-14下午02:38:39
	 * @throws IOException 
	 */
	public String listChildPage() throws IOException {
		List<AppPageTab> lstPage = appPageService.getAllChildrenPageById(getUserInfo().getAppId(), null);
		if (lstPage == null) {
			// 该导航没有页面
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		} else {
			this.setLstAppPage(lstPage);
			return SUCCESS;
		}
	}
	
	/**
	 * 获取导航页面树结构
	 * @return
	 * @author liuhj
	 * 2012-7-14下午05:56:25
	 * @throws IOException 
	 */
	public String generatePageNavigationTree() throws IOException {
		if (getUserInfo().getAppId() == null || getUserInfo().getAppId() == 0) {
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		}
		String json = appPageService.generatePagesTree(getUserInfo().getAppId());
		if (json != null) {
			jsonOut(json);
		} else {
			jsonOut(GenericConstants.OPERATION_NULL);
		}
		return null;
	}
	
	/**
	 * 查询页面内容
	 * @return
	 * @author liuhj
	 * 2012-7-17下午10:11:45
	 * @throws IOException 
	 */
	public String viewPageContent() throws IOException {
		JSONObject jo = JSONObject.fromObject(json);
		StringBuffer result = new StringBuffer();
		result.append("{\"pageContent\":");
		result.append(appPageService.generatePageContentById(jo.getInt("id"),
				jo.getInt("isFirstPage"), jo.getInt("isContentList"), jo.getInt("isMorePage")));
		result.append("}");
		jsonOut(result.toString());
		return null;
	}
	
	/**
	 * 我的素材上传
	 * @return
	 * @author liuhj
	 * 2012-7-16下午04:08:47
	 * @throws UnsupportedEncodingException 
	 */
	public String myMaterialUpload() throws UnsupportedEncodingException {
		String iconName = FileUploadUtil.getParamsFromRequest(request);
		iconName = URLDecoder.decode(iconName, "GBK");
		String fileName = FileUploadUtil.generateIconName()+GenericConstants.MYAPP_ICON_SUFFIX;
		String imgURLPath = getImgBasePath()+ImgAndFilePath.ENTERP_ICON+File.separator + fileName;
		String imgDiskPath = getWebAppsRealPath() + imgURLPath;
		FileUploadUtil.fileUpload(imgDiskPath, request,GenericConstants.REQUEST_HEADER_LENGTH);//上传
		//保存
		AppIconTab icon = new AppIconTab();
		icon.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		icon.setIntIconType(GenericConstants.ICON_TYPE_TITLE);
		icon.setIntIconDefineType(GenericConstants.ICON_DEFINE_TYPE_USER);
		String iconUrl = getServerURL()+imgURLPath.replace("\\", "/");
		icon.setVarIconUrl(imgURLPath.replace("\\", "/"));
		icon.setIntAppId(getUserInfo().getAppId());
		icon.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		icon.setIntIconName(FilenameUtils.getBaseName(iconName));
		Integer iconId = appIconService.save(icon);
		icon.setIntIconId(iconId);
		//返回icon服务器上的URL
		icon.setVarIconUrl(iconUrl);
		this.setAppIcon(icon);
		return SUCCESS;
	}
	
	/**
	 * 获取图标素材
	 * @return
	 * @author liuhj
	 * 2012-7-16下午03:42:51
	 * @throws IOException 
	 */
	public String listAllIcons() throws IOException {
		JSONObject jo = JSONObject.fromObject(json);
		Integer icon_define_type = Integer.parseInt(jo.get("icon_define_type").toString());
		List<AppIconTab> icons = appIconService.getMaterialIcons(getUserInfo()
				.getAppId(), icon_define_type);
		if (icons == null) {
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		} else {
			this.setLstAppIcon(icons);
			return SUCCESS;
		}
	}
	
	/**
	 * 隐藏用户上传的图标
	 * @author Taylor
	 * 2012-11-11 上午10:54:25
	 * @return
	 * @throws IOException
	 * String
	 */
	public String deleteUserIcon() throws IOException {
		int iconId = JSONObject.fromObject(json).getInt("intIconId");
		appIconService.updateHideIcon(iconId);
		jsonOut(GenericConstants.OPERATION_SUCCESS);
		return null;
	}
	
	/**
	 * 获取页面模版风格系列
	 * @return
	 * @author liuhj
	 * 2012-7-17下午10:08:50
	 * @throws IOException 
	 */
	public String listModuleStyles() throws IOException {
		List<ModuleStyleTab> lstStyles = appPageService.getAllModuleStyle();
		if (lstStyles == null || lstStyles.size() <= 0) {
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		}
		this.setLstModuleSytle(lstStyles);
		return SUCCESS;
	}
	
	/**
	 * 根据ID获取风格系列的具体展现样式
	 * @return
	 * @author liuhj
	 * 2012-7-17下午10:15:58
	 * @throws IOException 
	 */
	public String listModuleDisplayStyles() throws IOException {
		List<ModuleStyleTab> lstStyles = appPageService.getAllModuleDisplayStyle(id);
		if (lstStyles == null || lstStyles.size() <= 0) {
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		}
		this.setLstModuleSytle(lstStyles);
		return SUCCESS;
	}
	
	/**
	 * 更新用户选择的页面板式
	 * @return
	 * @author liuhj
	 * 2012-7-17下午10:28:23
	 */
	public String updatePageModuleStyle() {
		JSONObject jo = JSONObject.fromObject(json);
		int pageId = Integer.parseInt(jo.get("pageId").toString());
		int styleId = Integer.parseInt(jo.get("styleId").toString());
		appPageService.updatePageModuleStyle(pageId, styleId);
		return null;
	}
	
	/**
	 * 保存应用页面
	 * @return
	 * @throws IOException
	 * @author liuhj
	 * 2012-7-24下午05:40:10
	 */
	public String savePage() throws IOException {
		json = URLDecoder.decode(json, "GBK");
		Integer result = appPageService.saveOrUpdatePage(json, getUserInfo());
		jsonOut(result.toString());
		return null;
	}
	
	/**
	 * 保存更多页面
	 * @return
	 * @throws IOException
	 * @author liuhj
	 * 2012-7-24下午05:40:10
	 */
	public String saveMorePage() throws IOException {
		json = URLDecoder.decode(json, "GBK");
		appPageService.saveOrUpdateMorePage(json, getUserInfo());
		jsonOut(GenericConstants.OPERATION_SUCCESS);
		return null;
	}
	
	/**
	 * 删除页面的视图分类对应
	 * @return
	 * @author liuhj
	 * 2012-7-25下午01:38:29
	 * @throws IOException 
	 */
	public String deleteViewCateRelation() throws IOException {
		JSONObject jo = JSONObject.fromObject(json);
		AppViewCatelogRalationTab relation = (AppViewCatelogRalationTab) JSONObject
			.toBean(jo, AppViewCatelogRalationTab.class);
		if (relation.getIntViewCateId() != -1) {
			appPageService.deleteViewCateRelation(relation);
		}
		jsonOut(GenericConstants.OPERATION_SUCCESS);
		return null;
	}
	
	/**
	 * 删除页面的视图
	 * @return
	 * @author liuhj
	 * 2012-7-25下午01:38:29
	 * @throws IOException 
	 */
	public String deleteView() throws IOException {
		int viewId = JSONObject.fromObject(json).getInt("id");
		if (viewId != -1 ) {
			appPageService.deleteView(viewId);
		}
		jsonOut(GenericConstants.OPERATION_SUCCESS);
		return null;
	}
	
	/**
	 * 删除更多的内容
	 * @return
	 * @author liuhj
	 * 2012-7-25下午01:38:29
	 * @throws IOException 
	 */
	public String deleteMoreContent() throws IOException {
		int intMoreContent = JSONObject.fromObject(json).getInt("id");
		if (intMoreContent != -1 ) {
			moreContentService.delete(intMoreContent);
		}
		jsonOut(GenericConstants.OPERATION_SUCCESS);
		return null;
	}
	
	/**
	 * 删除更多的视图
	 * @return
	 * @author liuhj
	 * 2012-7-25下午01:38:29
	 * @throws IOException 
	 */
	public String deleteMoreView() throws IOException {
		int viewId = JSONObject.fromObject(json).getInt("id");
		if (viewId != -1 ) {
			moreContentService.deleteView(viewId);
		}
		jsonOut(GenericConstants.OPERATION_SUCCESS);
		return null;
	}
	
	/**
	 * 获取分类属性，如果不是最后一级，根据分类ID为0查询
	 * 			如果是最后一级，查询本级及所有上级分类属性
	 * @return
	 * @throws IOException
	 * @author liuhj
	 * 2012-7-28下午03:49:42
	 */
	public String viewCateAttributes() throws IOException {
		CatelogTab catelog = (CatelogTab) JSONObject.toBean(JSONObject
				.fromObject(json), CatelogTab.class);
		List<AttributeTab> attributes = appPageService
				.getAttributesByCateId(catelog);
		if (attributes == null || attributes.size() <= 0) {
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		}
		this.setLstAttributes(attributes);
		return SUCCESS;
	}
	
	/**
	 * 查询更多里功能事件类型
	 * @return
	 * @author liuhj
	 * 2012-8-13下午07:39:07
	 * @throws IOException 
	 */
	public String viewMoreActionList() throws IOException {
		List<TypeDto> lstType = appPageService.getMoreActionList(getUserInfo().getAppId());
		if (lstType == null || lstType.size() <= 0) {
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		}
		this.setLstTypes(lstType);
		return SUCCESS;
	}
	
	/**
	 * 获取视图内可用于排序的字段
	 * @author Taylor
	 * 2012-11-20 下午05:23:07
	 * @return
	 * String
	 * @throws IOException 
	 */
	public String listSortColumns() throws IOException {
		JSONObject jo = JSONObject.fromObject(json);
		JSONArray ja = new JSONArray();
		int intViewId = jo.getInt("intViewId");
		int intCateId = jo.getInt("intCateId");
		if (intViewId <= 0 || intCateId <= 0) {
			jsonOut(GenericConstants.OPERATION_NULL);
		} else {
			ja.add(dataSortService.getSortColumnsByIds(intViewId, intCateId));
			jsonOut(ja.toString());
		}
		return null;
	}
	
	/**
	 * 查询自定义页面
	 * @author Taylor
	 * 2012-11-20 下午05:23:07
	 * @return
	 * String
	 * @throws IOException 
	 */
	public String viewCustomPages() throws IOException {
		lstAppPage = appPageService.getCustomPages(getUserInfo().getAppId());
		if(lstAppPage==null || lstAppPage.size() <=0){
			jsonOut(GenericConstants.OPERATION_NULL);
			return null;
		} 
		return SUCCESS;
	}
	
	/**
	 * 查询自定义页面树形结构
	 * @author Taylor
	 * 2012-11-20 下午05:23:07
	 * @return
	 * String
	 * @throws IOException 
	 */
	public String viewCustomPageTree() throws IOException {
		String result = appPageService.getCustomPageTree(json);
		if (result != null) {
			jsonOut(result);
		} else {
			jsonOut(GenericConstants.OPERATION_NULL);
		}
		return null;
	}
	
	/**
	 * 获取用户信息绑定字段
	 * @author Taylor
	 * 2013-3-26 下午05:23:07
	 * @return
	 * String
	 * @throws IOException 
	 */
	public String listUsersBindColumns() {
		userFields = fieldService.getUserFieldsByAppId(getUserInfo().getAppId());
		return SUCCESS;
	}
	
	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}

	public List<PageNavigationTab> getListPageNavigation() {
		return listPageNavigation;
	}

	public void setListPageNavigation(List<PageNavigationTab> listPageNavigation) {
		this.listPageNavigation = listPageNavigation;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public List<AppPageTab> getLstAppPage() {
		return lstAppPage;
	}

	public void setLstAppPage(List<AppPageTab> lstAppPage) {
		this.lstAppPage = lstAppPage;
	}

	public List<AppIconTab> getLstAppIcon() {
		return lstAppIcon;
	}

	public void setLstAppIcon(List<AppIconTab> lstAppIcon) {
		this.lstAppIcon = lstAppIcon;
	}

	public String getImgIconUrl() {
		return imgIconUrl;
	}

	public void setImgIconUrl(String imgIconUrl) {
		this.imgIconUrl = imgIconUrl;
	}

	public List<ModuleStyleTab> getLstModuleSytle() {
		return lstModuleSytle;
	}

	public void setLstModuleSytle(List<ModuleStyleTab> lstModuleSytle) {
		this.lstModuleSytle = lstModuleSytle;
	}

	public AppIconTab getAppIcon() {
		return appIcon;
	}

	public void setAppIcon(AppIconTab appIcon) {
		this.appIcon = appIcon;
	}

	public List<PageNavigationDto> getLstPageNavigationDto() {
		return lstPageNavigationDto;
	}

	public void setLstPageNavigationDto(List<PageNavigationDto> lstPageNavigationDto) {
		this.lstPageNavigationDto = lstPageNavigationDto;
	}

	public List<AttributeTab> getLstAttributes() {
		return lstAttributes;
	}

	public void setLstAttributes(List<AttributeTab> lstAttributes) {
		this.lstAttributes = lstAttributes;
	}

	public List<TypeDto> getLstTypes() {
		return lstTypes;
	}

	public void setLstTypes(List<TypeDto> lstTypes) {
		this.lstTypes = lstTypes;
	}

	public List<SortColumnsDto> getSortColumns() {
		return sortColumns;
	}

	public void setSortColumns(List<SortColumnsDto> sortColumns) {
		this.sortColumns = sortColumns;
	}

	public List<Field> getUserFields() {
		return userFields;
	}

	public void setUserFields(List<Field> userFields) {
		this.userFields = userFields;
	}
}
